<?php

namespace App\Service\product;

use App\Models\product\ProductClassModel;
use App\Models\product\ProductModel;
use App\Models\product\ProductPopularizeModel;
use App\Models\product\ProductSonModel;
use App\Models\product\ProductUserQrcodeModel;
use App\Models\users\UsersModel;
use App\Service\users\UsersService;
use Carbon\Carbon;
use Illuminate\Support\Facades\Log;
use lxs\aliyun\AliyunQrcode;
use lxs\config\BaseStatic;
use lxs\tiktok\DyQrcode;
use lxs\tools\Tools;
use lxs\wechat\WeChatApplet;

class ProductApiService extends BaseStatic
{


    /**
     * 获取产品分类列表
     */
    public static function getProductClassList(): array
    {
        $classHeader = ['id' => '0', 'class_name' => '全部类型'];
        $data = ProductClassModel::where('deleted_at', 0)->orderBy('sort', 'asc')->orderBy('update_at', 'desc')->get()->toArray();
        return array_merge([$classHeader], $data);
    }


    /**
     * 获取推广广场页面数据(wechat)
     * @param $online_platform
     * @param $type
     * @param bool $isMore
     */
    public function getProductSquareData($online_platform, $type, bool $isMore = true): array
    {

        $model = ProductClassModel::with(['productList' => function ($query) use ($online_platform, $isMore) {
            $query->where('deleted_at', 0)
                ->where('online_platform', $online_platform)
//                ->whereRaw("FIND_IN_SET('" . $platform_id ."', popularize_platform)")
                ->where('status', 1);
            if (!$isMore) {
                $query->limit(3);
            }
        }])
            ->where('deleted_at', 0);
        if ($type && $type > 0) {
            $model->where('id', $type);
        }
        $lists = $model->orderBy('sort', 'asc')
            ->orderBy('update_at', 'desc')
            ->get()
            ->toArray();

        $lists = array_filter($lists, function ($item) {
            return count($item['product_list']) > 0;
        });

        foreach ($lists as &$list) {
            foreach ($list['product_list'] as &$product) {
                $product['product_id'] = productSonModel::where('product_id', $product['id'])->orderBy('popularize_id')->value('id');
            }
        }

        return self::serviceReturn(200, '获取产品广场页面数据成功', [
            'online_platform_data' => ProductModel::getOnlinePlatform(),
            'class_list' => self::getProductClassList(),
            'lists' => $lists,
        ]);

    }


    /**
     * 获取产品详情页面数据
     */
    public function getProductDetailData($product_id, $popularize_platform, $uid): array
    {
        $userInfo = UsersService::instance()->getUserInfo($uid);

        $product = ProductModel::with([
                'productSon' => function ($query) {
                    $query->orderBy('popularize_id');
                }
            ])
            ->where('id', $product_id)
            ->where('deleted_at', 0)
            ->first();
        if (!$product) {
            return self::serviceReturn(400, '产品不存在');
        }

        if ($popularize_platform > 0) {
            foreach ($product->productSon as $son) {
                if ($son->product_id == $product->id && $son->popularize_id == $popularize_platform) {
                    $product->productSon = $son;
                    break;
                }
            }
        } else {
            $product->productSon = reset($product->productSon)[0];
        }

        $popularize_name = ProductPopularizeModel::where('id', $product->productSon->popularize_id)->value('popularize_name');
        $product->product_title = $product->product_title . '(' . $popularize_name . ')';
        $product->live_time = Carbon::createFromTimestamp($product->live_time)->format('Y-m-d');

        $param = '?'. Tools::getQrcodeCode($userInfo->unique_id, $product->productSon->id);
        $product->productSon->platform_link = $product->productSon->platform_link . $param;
        $product->productSon->path = $product->productSon->path . $param;

        $product->popularize_qrcode = ProductUserQrcodeModel::where('product_id', $product->productSon->id)
            ->where('uid', $uid)
            ->value('qrcode');
        if (!$product->popularize_qrcode) {
            $product->popularize_qrcode = $this->productQrcode($product->productSon->id, $product->productSon->popularize_id, $uid, $userInfo->unique_id, $product->productSon->appid, $product->productSon->secret, $product->productSon->public_key);
        }

        // 获取推广平台
        $popularize_platform_data = ProductPopularizeModel::whereIn('id', explode(',', $product->popularize_platform))->get()->toArray();

        return self::serviceReturn(200, '获取产品详情页面数据成功', [
            'user_info' => $userInfo,
            'product' => $product,
            'popularize_platform_data' => $popularize_platform_data
        ]);

    }


    /**
     * 获取推广广场页面数据（web)
     */
    public function getProductSquareDataWeb($online_platform, $type): array
    {

        $model = ProductModel::where('deleted_at', 0)
            ->where('online_platform', $online_platform)
//            ->whereRaw("FIND_IN_SET('" . $online_platform ."', platform_ids)")
            ->where('status', 1);

        if ($type) {
            $model->where('class_id', $type);
        }
        $lists = $model->orderBy('sort', 'asc')->orderBy('sort_pid', 'asc')->get()->toArray();

        $lists = array_map(function ($item) {
            $online_platform_name = ProductModel::getOnlinePlatform($item['online_platform']);
            $item['product_title'] = $item['product_title'] . '(' . $online_platform_name . ')';

            $item['popularize_data'] = ProductPopularizeModel::whereIn('id', explode(',', $item['popularize_platform']))->get()->toArray();

            $item['live_time'] = Carbon::createFromTimestamp($item['live_time'])->format('Y-m-d');

            return $item;
        }, $lists);

        return self::serviceReturn(200, '获取产品广场页面数据成功', [
            'online_platform_data' => ProductModel::getOnlinePlatform(),
            'class_list' => self::getProductClassList(),
            'lists' => $lists,
        ]);

    }


    /**
     * 产品推广二维码
     * @param $product_id
     * @param $popularize_id
     * @param $uid
     * @param $unique_id
     * @param $appid
     * @param $secret
     * @param $publicKey
     * @return string|bool
     */
    public function productQrcode($product_id, $popularize_id, $uid, $unique_id, $appid, $secret, $publicKey=null): string|bool
    {
        if ( $appid && $secret ) {

            $param = Tools::getQrcodeCode($unique_id, $product_id);
            $qrcode = match ($popularize_id) {
                1 => (new WeChatApplet())->getMiniCode('pages/index/index', $param, 300, $appid, $secret),
                2 => (new DyQrcode())->getMiniCode('pages/index/index', $param, 300, $appid, $secret),
                3 => (new AliyunQrcode($appid, $secret, $publicKey))->getMiniCode('pages/index/index', $param),
                default => false
            };
            if ($qrcode) {
                $platform_qrcode = new ProductUserQrcodeModel();
                $platform_qrcode->uid = $uid;
                $platform_qrcode->product_id = $product_id;
                $platform_qrcode->qrcode = $qrcode;
                $platform_qrcode->save();
            }
            return $qrcode;

        }
        return false;
    }


    /**
     * 自动创建产品推广二维码
     * @param $uid
     * @param $product_id
     * @return void
     */
    public function createProductQrcode($uid, $product_id): void
    {
        $userInfo = UsersModel::where('id', $uid)->first();
        if (!$userInfo) return;
        $product = ProductSonModel::where('id', $product_id)->first();
        $popularize_qrcode = ProductUserQrcodeModel::where('product_id', $product->id)
            ->where('uid', $uid)
            ->value('qrcode');
        if (!$popularize_qrcode) {
            $qrcode = $this->productQrcode($product->id, $product->popularize_id, $userInfo->id, $userInfo->unique_id, $product->appid, $product->secret, $product->public_key);
            if ($qrcode) log::info('创建产品推广二维码成功');
        }
    }


}
